<?php

defined('EXEC') or die();
$transacao = 'relacionamento';

if(!$auth->isRead($transacao)){
	Util::info(Config::AUTH_MESSAGE);
	return true;
}

//Importando a classes
Loader::import('com.atitudeweb.SQL');

////////////////////////

//CRUD atitudeweb 1.0 //

////////////////////////

$form 			= false;

$rowEdit 		= array();

$table 			= 'tethys.tb_relacionamento';

$tablepk 		= 'ci_relacionamento';

$limitPagina 	= 10; //Registros por p�gina

$faixa 			= 10; //Faixa de p�ginas que ir�o ser mostradas pagina��o (google)

$dif 			= 5; //A diferen�a que a faixa de p�ginas ir�o come�ar a caminhar (google)

$p 				= (@$_GET['p'] ? $_GET['p'] : 1);



//Exclus�o de v�rios ou um registro

if(isset($_GET['del'])){

	if(is_numeric($_GET['del'])){

		$values = array();

		for($i=0; $i<$_GET['del']; $i++){

			if(is_numeric(@$_POST['checkdel_'.$i])){

				$values[] = $_POST['checkdel_'.$i];

			}

		}

		Util::growl('Aviso', 'Exclu�do com sucesso!', 'ok');

		if(count($values) > 0){

			if(!SQL::remove($table, $tablepk, $values)){

				Util::alert('Verifique se esta transa��o est� sendo utilizada!');

			}

		}

	}

}



//Altera��o ou inclus�o de um registro

if(isset($_GET['db']) && isset($_GET['form'])){

	if($_GET['db'] == 1 && $_GET['form'] == 0){

		$nm_relacionamento="'".$_POST['nm_relacionamento']."'";

		$fl_ativo = $_POST['fl_ativo'];



		if (empty($fl_ativo)){

			$fl_ativo= "'N'";

		}else{

			$fl_ativo= "'".$fl_ativo."'";

		}

		$nm_usuario = "'".strtoupper($user['nm_login'])."'";

		$insert = 'insert into tethys.tb_relacionamento (nm_relacionamento, dt_cadastro,usr_cadastro,fl_ativo)

		values (upper('.$nm_relacionamento.'),now(),'.$nm_usuario.','.$fl_ativo.');';

		//echo $insert;

		//die;

		Connection::exec($insert);

		Controller::setInfo('RELACIONAMENTO(S)', 'Registro salvo com sucesso!');

		Controller::redirect(Util::setLink(array('form=null', 'db=null')));

	}

	elseif($_GET['db'] == 1 && $_GET['form'] > 0){

		SQL::update($table, $_POST, array($tablepk => $_GET['form']));

		Controller::setInfo('RELACIONAMENTO(S)', 'Registro adicionado com sucesso!');

		Controller::redirect(Util::setLink(array('form=null', 'db=null')));

	}

}





//Mudan�a do formul�rio para adi��o ou altera��o de registro

if(isset($_GET['form'])){

	if($_GET['form'] == 0){
		$btFormLabel = 'Adicionar';
	}
	else{
		$btFormLabel = 'Salvar';
		$rowEdit = SQL::getRows($table, array($tablepk => $_GET['form']), null, true);
	}
	$form = true;
}



//Consulta no banco e mec�nica de pagina��o

if(isset($_POST['search1']) || !$form){

	if(isset($_POST['search1'])){

		$term = addslashes($_POST['search1']);

		$where =  "nm_relacionamento ilike '%{$term}%'   ";

		$registros = SQL::getNumTable($table, $where);

		$query = SQL::getRows($table, null, $where, false, (($p - 1) * $limitPagina), $limitPagina, 'ci_relacionamento asc');
	}
	else{
		$registros = SQL::getNumTable($table, $where);
		$query = SQL::getRows($table, null, $where, false, (($p - 1) * $limitPagina), $limitPagina, 'ci_relacionamento asc');
	}

	$paginas = ceil($registros / $limitPagina);

	$dif = $p - ($faixa / 2);

	$min = 1;

	$max = ($paginas > $faixa ? $faixa : $paginas);

	if($dif > 0){

		$min += $dif;

		$min = ($min > ($paginas - $faixa) ? ($paginas - $faixa) : $min);

		$max += $dif;

		$max = ($max > $paginas ? $paginas : $max);

	}

	if($p == 1)

	$back = 1;

	else

	$back = $p - 1;



	if($p == $paginas)

	$next = $paginas;

	else

	$next = $p + 1;

}

?>

<div id="container">



	<div style="overflow: hidden;">

		<table width="100%" border="0" cellpadding="0" cellspacing="0">

			<tr>
				<td width="40"><img src="assets/transacao.png" /></td>

				<td><div
						style="font-size: 14px; font-weight: bold; float: left; padding: 5px; margin-right: 20px;">Relacionamentos</div>

						<?php if($form){ ?>
				</td>
				<td align="right">

					<button id="btVoltar" onclick="window.location='?page=documentos';">Voltar</button>

					<?php } else{ ?>

					<div style="float: left">

						<form
							action="<?php echo Util::setLink(array('del=null', 'p=null')); ?>"
							method="post">

							<div>

								<input type="text" name="search1" id="search1"
									value="<?php echo @$_POST['search1']; ?>"
									class="text ui-widget-content ui-corner-all" />&nbsp;

								<button id="btSearch" class="bt" title="Pesquisar">Pesquisar</button>

							</div>

						</form>
					</div>
				</td>
				<td align="right">

					<button id="btVoltar" onclick="window.location='?page=documentos';">Voltar</button>

					<button id="btAdd" class="bt" title="Adicionar">Adicionar</button>

					<?php } ?>
				</td>
			</tr>

		</table>

	</div>



	<?php if($form){ ?>

	<form action="<?php echo Util::setLink(array('db=1')) ?>" method="post"
		id="formInsertEdit" onsubmit="return test();">

		<table border="0" align="center">

			<tr>
				<td></td>
				<td><div class="validateTips">Preencha corretamente o formul�rio.</div>
				</td>
			</tr>

			<tr>

				<td align="right">Forma de Pagamento: *</td>

				<td><input type="text" id="nm_relacionamento"
					name="nm_relacionamento"
					value="<?php echo trim(@$rowEdit['nm_relacionamento']); ?>"
					class="text ui-widget-content ui-corner-all" size="30" /></td>

			</tr>

			<tr>

				<td align="right">Ativo: *</td>

				<td><input type="checkbox" id="fl_ativo" name="fl_ativo" value="S"
					class="text ui-widget-content ui-corner-all" size="30" /></td>

			</tr>

			<tr>

				<td></td>

				<td><button id="btInsertEdit" type="submit">
				<?php echo $btFormLabel; ?>
					</button></td>

			</tr>

		</table>

	</form>



	<?php } else{ ?>
	<form
		action="<?php echo Util::setLink(array('del='.$query->rowCount())) ?>"
		method="post" id="formSearch">

		<table class="tablelist ui-widget ui-widget-content">

			<thead>

				<tr class="ui-widget-header">

					<th width="25" class="check"><input type="checkbox" id="btCheckAll" />
					</th>

					<th>ID</th>

					<th>Relacionamento</th>

					<th></th>

				</tr>

			</thead>

			<tbody>

			<?php

			$count = 0;

			while($row = $query->fetch()){

				echo '<tr>

		            	<td class="check"><input type="checkbox" class="btCheck" name="checkdel_'.$count.'" value="'.$row[$tablepk].'"/></td>

		                <td>'.$row['ci_relacionamento'].'</td>

		                <td>'.$row['nm_relacionamento'].'</td>

		                <td width="30" align="center">

		                	<div onclick="window.location=\''.Util::setLink(array('form='.$row[$tablepk], 'del=null')).'\';" class="btEdit ui-widget ui-helper-clearfix" title="Editar">

						    	<div class="ui-state-default ui-corner-all"><span class="ui-icon ui-icon-pencil"></span></div>

						    </div>				    

		                </td>

		        	</tr>';

				$count++;

			}

			?>

			</tbody>

		</table>

	</form>

	<div>

		<button id="btDel" class="bt" title="Excluir selecionados">Excluir</button>

		<div style="float: right; padding-top: 8px;">
		<?php echo 'P�gina '.$p.' de '.$paginas; ?>
		</div>

	</div>

	<table border="0" cellpadding="1" cellspacing="0" align="center">
		<tr>

		<?php

		if ($registros > 0) {

			echo '<form id="formPaginacao" name="formPaginacao" method="post">

		<td><div onclick="setPaginacao(\''.Util::setLink(array('p='.$back)).'\')" class="buttonPag back ui-state-default ui-corner-all" style="padding-left:4px;"><span class="ui-icon ui-icon ui-icon-carat-1-w"></span></div></td>';

			for($i=$min;$i<=$max;$i++){

				if($i == $p)

				echo '<td><div onclick="setPaginacao(\''.Util::setLink(array('p='.$i)).'\')" class="buttonPag ui-state-default ui-corner-all"><u>'.$i.'</u></div></td>';

				else

				echo '<td><div onclick="setPaginacao(\''.Util::setLink(array('p='.$i)).'\')" class="buttonPag ui-state-default ui-corner-all">'.$i.'</div></td>';

			}

			echo '<td><div onclick="setPaginacao(\''.Util::setLink(array('p='.$next)).'\')" class="buttonPag ui-state-default ui-corner-all" style="padding-left:4px;"><span class="ui-icon ui-icon-carat-1-e"></span></div></td>

		<input type="hidden" name="search1" value="'.@$_POST['search1'].'"/>

		</form>';

		}

		?>

		</tr>
	</table>
	<br>

	<div align="center">
	<?php echo Util::descrRows($registros); ?>
	</div>



	<?php } ?>

	<script>

$(function(){

	$("#nm_relacionamento").keyup(function(){

		$(this).val($(this).val().toUpperCase());

	    var varString = $(this).val();

	    var stringAcentos = ('����������������������������');

	    var stringSemAcento = ('aaeouaoaeioucuAAEOUAOAEIOUCU');

	    

	    var i = new Number();

	    var j = new Number();

	    var cString = new String();

	    var varRes = '';

	    

	    for (i = 0; i < varString.length; i++) {

	        cString = varString.substring(i, i + 1);

	        for (j = 0; j < stringAcentos.length; j++) {

	            if (stringAcentos.substring(j, j + 1) == cString){

	                cString = stringSemAcento.substring(j, j + 1);

	            }

	        }

	        varRes += cString;        

	    }

	    varRes = varRes.replace( /\s/g, '' );

	});

});

</script>